package com.jfire.json.serializer;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.jfire.baseutil.collection.ObjectCollect;
import com.jfire.baseutil.collection.StringCache;
import com.jfire.json.field.JsonField;
import com.jfire.json.util.JsonSerializer;

public class CalendarSerializer implements JsonSerializer
{
    private static DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    @Override
    public Object transToJsonvalue(Object src, ObjectCollect collect)
    {
        return format.format(new Date(((Calendar) src).getTimeInMillis()));
    }
    
    @Override
    public void setJsonFields(JsonField[] jsonFields)
    {
    }
    
    @Override
    public void writeToString(StringCache cache, Object value, ObjectCollect collect)
    {
        cache.append('"').append(format.format(new Date(((Calendar) value).getTimeInMillis()))).append('"');
    }
    
    @Override
    public Object toBean(Object value, Type type)
    {
        if (value instanceof String)
        {
            try
            {
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(format.parse((String) value).getTime());
                return calendar;
            }
            catch (ParseException e)
            {
                throw new RuntimeException(e);
            }
        }
        else
        {
            return value;
        }
    }
}
